package br.com.mensures.mbean;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.imageio.ImageIO;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

@RequestScoped
@ManagedBean
public class GraficoMBean extends PageCodeBase {
	
	private StreamedContent chart;
    
	public GraficoMBean() {
		
		//this.chart = chart;
		
		 ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); 
		 BufferedImage pageImage=gerarGrafico(info);
		
	}

	private BufferedImage gerarGrafico(ChartRenderingInfo info) {
		// TODO Auto-generated method stub
		
		
		 try {  
			             /*  
			            BufferedImage bufferedImg = new BufferedImage(100, 25, BufferedImage.TYPE_INT_RGB);  
			             Graphics2D g2 = bufferedImg.createGraphics();  
			             g2.drawString("This is a text", 0, 10);  
			             ByteArrayOutputStream os = new ByteArrayOutputStream();  
			             ImageIO.write(bufferedImg, "png", os);  
			             graphicText = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png"); */  
			               
			            //Chart  
			            JFreeChart jfreechart = ChartFactory.createPieChart("Turkish Cities", createDataset(), true, true, false);  
			            File chartFile = new File("dynamichart");  
			            ChartUtilities.saveChartAsPNG(chartFile, jfreechart, 375, 300);  
			            chart = new DefaultStreamedContent(new FileInputStream(chartFile), "image/png");  
			 
			         } catch (Exception e) {  
			             e.printStackTrace();  
			         }  

		
		return null;
	}
	
	 private PieDataset createDataset() {  
		         DefaultPieDataset dataset = new DefaultPieDataset();  
		        dataset.setValue("Istanbul", new Double(45.0));  
		         dataset.setValue("Ankara", new Double(15.0));  
		         dataset.setValue("Izmir", new Double(25.2));  
		         dataset.setValue("Antalya", new Double(14.8));  
		        return dataset;  
   }  


	public StreamedContent getChart() {
		return chart;
	}

	public void setChart(StreamedContent chart) {
		this.chart = chart;
	}  

}
